package com.leyou.sms.Utils;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.leyou.commons.utils.JsonUtils;
import com.leyou.sms.config.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Map;

import static com.leyou.sms.Constants.SmsConstants.*;
/**
 * 短信发送工具类
 */
@Slf4j
@Component
public class LySMSUtils {
	@Autowired
	private  IAcsClient client;

	@Autowired
	private SmsProperties prop;


	public void  sendCode(String phoneNumber,String code) {
		CommonRequest request = new CommonRequest();
		request.setProtocol(ProtocolType.HTTPS);
		request.setMethod(MethodType.POST);
		request.setDomain(prop.getDomain());
		request.setVersion(prop.getVersion());
		request.setAction(prop.getAction());
		request.putQueryParameter(SMS_PARAM_KEY_PHONE, phoneNumber);
		request.putQueryParameter(SMS_PARAM_KEY_SIGN_NAME,prop.getSignName());
		request.putQueryParameter(SMS_PARAM_KEY_TEMPLATE_CODE,prop.getVerifyCodeTemplate());
		request.putQueryParameter(SMS_PARAM_KEY_TEMPLATE_PARAM,  "{\"code\":\""+code+"\"}");

		try {
			CommonResponse response = client.getCommonResponse(request);
			if (response.getHttpStatus() >= 300) {
				log.error("【SMS服务】发送短信失败。响应信息：{}", response.getData());
			}
			// 获取响应体
			Map<String, String> resp = JsonUtils.toMap(response.getData(), String.class, String.class);
			// 判断是否是成功
			if (!StringUtils.equals(OK, resp.get(SMS_RESPONSE_KEY_CODE))) {
				// 不成功，
				log.error("【SMS服务】发送短信失败，原因{}", resp.get(SMS_RESPONSE_KEY_MESSAGE));
			}
			log.info("【SMS服务】发送短信成功，手机号：{}, 响应：{}", phoneNumber, response.getData());
		} catch (ServerException e) {
			log.error("【SMS服务】发送短信失败，服务端异常。", e);
		} catch (ClientException e) {
			log.error("【SMS服务】发送短信失败，客户端异常。", e);
		}
	}
}
